<?php

namespace Home\Controller;

use Common\Controller\BaseController;
use Common\Model\ArticleModel;
use Common\Model\BbsModel;
use Common\Model\ClassModel;
use Common\Model\DocModel;
use Common\Model\LogModel;
use Common\Model\MsgModel;
use Common\Model\OrgModel;
use Common\Model\UserBbsModel;
use Common\Model\UserCountModel;
use Common\Model\UserDocModel;
use Common\Model\UserOrgModel;
use Common\Model\UserModel;
use Common\Model\UserPDocModel;

class UserController extends BaseController {

    /**
     * 展示用户的个人中心
     */
    public function index(){
        $uid = I('get.uid', 0);;
        if(!$uid){
            $this->error('访问异常，请稍后再试！');
        }
        $user = UID == $uid ? $this->user : UserModel::getUserById($uid);
        if(!$user){
            $this->error('您所访问的用户数据异常，请稍后再试！');
        }
        // 获取管理的团体以及获取关注的BBS
        $orgs = UserOrgModel::getUserOrgsInfo($uid);
        $bbss = UserBbsModel::getUserBbssInfo($uid);
        $signs = $user['signs'];                // 用户的连续登陆次数
        if(date('Ymd', $user['sign']) === date('Ymd')){      // 如果今天已登录
            $signed = 1;
        }else{
            $signed = 0;
            if(date('Ymd', $user['sign']) !== date('Ymd', time() - 86400)){     // 如果昨天没登录
                $signs = 0;
            }
        }
        if ($uid != UID) {
            $this->assign('user', $user);
            $this->assign('gx', $this->user['gx']);
            UserCountModel::update($uid, 'visit');
            $docs = UserPDocModel::getUserPDocsInfo($uid, UserPDocModel::NORMAL);
        } else {
            $docs = UserPDocModel::getUserPDocsInfo($uid);
        }
        $this->assign('signed', $signed);    // 判断今天是否已签到
        // 判断昨天是否已经签到？如果昨天没有签到，则显示0天，否则显示签到天数
        $this->assign('signs', $signs);
        $this->assign('auth', $uid == UID ? 1 : 0);     // 验证是否是本人
        $this->assign('collets', UserDocModel::getCollectedCount($uid) ? : '');
        $this->assign('orgs', $orgs);
        $this->assign('bbss', $bbss);
        $this->assign('docs', $docs);
        $this->assign('title', $user['nick'].' - 个人中心');
        $this->assign('description', '用户'.$user['nick'].'的个人中心，展示该用户'.$user['nick'].'的基本信息与其管理的团体信息和关注的社区信息，用户登陆后可进行签到获取贡献度！');
        $this->display();
    }

    /**
     * 用户调用AJAX进行签到
     * 连续1-10天得1点，11-100天得2点，101天以上得3点
     */
    public function ajaxsign(){
        if(!UID){
            json(400, '签到需要登陆');
        }
        $user = $this->user;
        if(date('Ymd', $user['sign']) === date('Ymd')){
            json(400, '您今天已经签到，请勿重复操作');
        }
        $signs = 1;   // 初始连续签到天数
        $addgx = 1;   // 初始增加的贡献度
        // 如果昨天签到了
        if(date('Ymd', $user['sign']) === date('Ymd', time() - 86400)){
            $signs = $user['signs'] + 1;
            if($signs > 10 && $signs < 101){
                $addgx = 2;
            }else if($signs > 100){
                $addgx = 3;
            }
        }
        $result = UserModel::sign(UID, $signs, $addgx);
        if(!$result){
            json(400, '签到失败，请刷新后再试');
        }
        json(200, '', ['gx' => $user['gx'] + $addgx, 'addgx' => $addgx]);
    }

    /**
     * 展示用户的收藏文档
     */
    public function collect(){
        $uid = I('get.uid', 0);
        $p = I('get.p', 1);     //页数
        $pcount = 8;            //每页显示数量
        $user = $uid == UID ? $this->user : UserModel::getUserById($uid);
        if(!$user){
            $this->error('用户数据异常，请稍后再试！');
        }
        $count = UserDocModel::getCollectedCount($uid);
        $list = $count ? UserDocModel::getUserDocsInfo($uid, $p, $pcount) : [DocModel::getDocById(1)];
        $this->assign('login', $uid == UID ? 1 : 0);  // 验证是否是本人
        if ($uid != UID) {
            $this->assign('user', $user);
            $this->assign('gx', $this->user['gx']);
            UserCountModel::update($uid, 'visit');
        }
        $this->assign('page', page($count, $pcount, $p));
        $this->assign('list', $list);
        $this->assign('auth', $uid == UID ? 1 : 0);     // 验证是否是本人
        $this->assign('collets', $count ? : 1);
        $this->assign('title', $user['nick'].' - 收藏文档');
        $this->assign('description', '用户'.$user['nick'].'收藏的文档中心，展示用户'.$user['nick'].'收藏的所有文档信息！');
        $this->display();
    }

    /**
     * 展示用户的消息
     */
    public function msg(){
        if(!UID){
            $this->error('您需要先登录账号！', U('/login@wooo.wang'));
        }
        $p = I('get.p', 1);    //页数
        $pcount = 15;          //每页显示数量
        $user = $this->user;
        if(!$user){
            $this->error('用户数据异常，请稍后再试！');
        }
        $data = MsgModel::getMsgs(UID, $p, $pcount);
        $html = '';
        if($data['list']){
            $todayDateStr = date('Y-m-d', time());    // 今天的日期字符串
            $prevDateStr = '';
            foreach($data['list'] as $key => $value){
                $dateTmpStr = date('Y-m-d', $value['create']);
                if($prevDateStr !== $dateTmpStr){
                    if($dateTmpStr === $todayDateStr){
                        $headerStr = '<h3>Today.</h3>';
                    }else{
                        $headerStr = '<h3>'.$dateTmpStr.'</h3>';
                    }
                    $prevDateStr = $dateTmpStr;
                }else{
                    $headerStr = '';
                }
                if($value['status'] == MsgModel::NORMAL){
                    $content = '<li data-mid="'.$value['id'].'" data-status="'.$value['status'].'" class="msgMark"><a href="'.U('/u/'.$value['sid']).'">'.$value['nick'].'</a> '.$value['content'].'<span class="icon-ok okBtn" title="标为已读"></span> <span class="icon-out dlBtn" title="删除"></span></li>';
                }else{
                    $content = '<li data-mid="'.$value['id'].'" data-status="'.$value['status'].'"><a href="'.U('/u/'.$value['sid']).'">'.$value['nick'].'</a> '.$value['content'].'<span class="icon-out dlBtn" title="删除"></span></li>';
                }
                $html .= $headerStr.$content;
            }
        }
        $this->assign('html', $html);
        $this->assign('page', page($data['count'], $pcount, $p));
        $this->assign('collets', UserDocModel::getCollectedCount(UID) ? : 1);
        $this->assign('title', $user['nick'].' - 消息通知');
        $this->assign('description', '用户'.$user['nick'].'的消息通知中心，展示用户'.$user['nick'].'收到的所有消息通知！');
        $this->display();
    }

    /**
     * 创建新团体
     */
    public function createbbs(){
        if(!UID){
            $this->error('您需要先登录账号', U('/login@wooo.wang'));
        }
        $user = $this->user;
        if(!$user){
            $this->error('用户数据异常，请稍后再试！');
        }
        if(IS_POST){
            $name = I('post.name', '');
            $desc = I('post.desc', '');
            $gx = (int)I('post.gx', 0);
            $cate = I('post.cateid', 0);
            if(!checkStrLength($name, 2) || !$desc || $gx < 0 || $gx > $user['gx']){
                $this->error('您提交的社区数据有误，请您重新提交！');
            }
            $data = [
                'name'  => $name,
                'desc'  => $desc,
                'class' => $cate,
                'gx' => $gx,
                'create'=> time()
            ];
            $bid = BbsModel::createBbs(UID, $gx, $data);
            if(!$bid){
                $this->error('社区创建失败，请稍后再试！');
            }
            $this->success('社区'.$name.'创建成功', U('/'.$bid.'@bbs.wooo.wang'));
        }else{
            $this->assign('cate', ClassModel::getCreateClass());
            $this->assign('collets', UserDocModel::getCollectedCount(UID) ? : 1);
            $this->assign('title', $user['nick'].' - 创建社区');
            $this->assign('description', '用户'.$user['nick'].'创建新的社区，社区聚集相同兴趣爱好的朋友一同愉快的交流互动，并可同时管理维护多份文档[DOC]！');
            $this->display();
        }
    }

    /**
     * 捐赠
     */
    public function donation()
    {
        if(!UID){
            json(400, '您需要先登陆');
        }
        $uid = I('get.uid', 0);
        $gx = I('post.gx', 0);
        if (!$uid || !$gx) {
            json(400, '参数错误');
        }
        if (UserModel::donationUser(UID, $uid, $gx)) {
            json(200, '捐赠成功，感谢有你');
        }
        json(400, '捐赠失败，请刷新后再试！');
    }

    /**
     * 设置用户信息
     */
    public function setUser(){
        if(!UID){
            $this->error('您需要先登录账号！', U('/login@wooo.wang'));
        }
        $user = $this->user;
        if(!$user){
            $this->error('用户数据异常，请稍后再试！');
        }
        if(IS_POST){
            $nick = I('post.nick', '');
            $avatar = I('post.avatar', '');
            $desc = I('post.desc', '');
            if(!checkStrLength($nick)){
                $this->error('您输入的昵称长度应为4~14个字符（一个汉字2个字符），请重新输入！');
            }
            $data = [
                'nick' => $nick,
                'avatar' => $avatar,
                'desc' => $desc
            ];
            $result = UserModel::update(UID, $data);
            if($result){
                $this->success('修改用户信息成功', U('/u/'.UID));
            }else{
                $this->error('修改用户信息失败，请稍后再试');
            }
        }else{
            $this->assign('token', qiniu());
            $this->assign('collets', UserDocModel::getCollectedCount(UID) ? : 1);
            $this->assign('title', $user['nick'].' - 设置账户');
            $this->assign('description', '设置用户'.$user['nick'].'的相关账户信息，如修改昵称、绑定邮箱等！');
            $this->display();
        }
    }

    /**
     * 使用Ajax标记消息为已读状态
     */
    public function ajaxokmsg(){
        $mid = I('post.mid', 0);    // 消息ID
        if(!UID || !$mid){
            json(400);
        }
        if(MsgModel::update(UID, $mid, ['status' => MsgModel::DELTEL])){
            json(200);
        }
        json(400);
    }

    /**
     * 使用Ajax删除用户的某条通知消息
     */
    public function ajaxdlmsg(){
        $mid = I('post.mid', 0);    // 消息ID
        $status = I('post.status', -2);
        if(!UID || !$mid || !in_array($status, [MsgModel::NORMAL, MsgModel::DELTEL])){
            json(400, '参数异常，请刷新后再试');
        }
        if(MsgModel::deleteMsg(UID, $mid, $status)){
            json(200);
        }
        json(400, '删除消息失败，请刷新后再试');
    }

    /**
     * 用户创建私人文档
     */
    public function createdoc(){
        if(!UID){
            $this->error('您需要先登录账号！', U('/login@wooo.wang'));
        }
        $user = $this->user;
        $docNum = UserPDocModel::getUserPDocsCount(UID, UserPDocModel::NORMAL_HIDE);     // 当前正常状态下的私有文档数量
        $needgx = $docNum >= 3 ? 1000 : pow(10, $docNum);
        $can = $user['gx'] - $needgx >= 0 ? 0 : 1;
        if(IS_POST){
            $name = I('post.name', '');
            $desc = I('post.desc', '');
            $cate = I('post.cateid', 0);
            if(!checkStrLength($name, 2) || !$desc || !$cate){
                $this->error('您提交的文档数据有误，请您重新提交！');
            }
            $class = ClassModel::getClassById($cate);
            if($class['pid'] == 0){
                $this->error('文档分类数据异常');
            }
            if($can === 1){
                $this->error('您的贡献度不足！');
            }
            $data = [
                'uid' => UID,
                'name' => $name,
                'desc' => $desc,
                'class' => $cate,
                'need_review' => DocModel::NEEDNOT_REVIEW,
                'create' => time()
            ];
            $did = DocModel::createPrivateDoc(UID, $needgx, $data);
            if(false === $did){
                $this->error('创建文档失败');
            }
            $this->success('您的私人文档「'.$name.'」创建成功，愿它与您一同成长，刚把爹！', U('/show/'.$did.'@doc.wooo.wang'), 3);
        }else{
            $this->assign('cate', ClassModel::getCreateClass());
            $this->assign('docnum', $docNum + 1);
            $this->assign('needgx', $needgx);
            $this->assign('cj', $can);
            $this->assign('title', $user['nick'].' - 创建私人文档');
            $this->assign('description', '用户'.$user['nick'].'创建私人文档，整理书写更多的知识与经验！'.$user['desc']);
            $this->display();
        }
    }

    /**
     * 私有文档提交记录
     */
    public function review()
    {
        $uid = I('get.uid', 0);
        $did = I('get.did', 0);
        $p = I('get.pid', 1);
        $pcount = 10;
        if (!$uid) {
            $this->error('参数异常');
        }
        $user = UID == $uid ? $this->user : UserModel::getUserById($uid);
        if(!$user){
            $this->error('您所访问的用户数据异常，请稍后再试！');
        }
        if ($uid != UID) {
            $this->assign('user', $user);
            $this->assign('gx', $this->user['gx']);
            UserCountModel::update($uid, 'visit');
        }
        $type = UID == $uid ? UserPDocModel::NORMAL_HIDE : UserPDocModel::NORMAL;
        $docs = UserPDocModel::getUserPDocsInfo($uid, $type, false);
        $articles = $did ? ArticleModel::getArticleList($did, $p, $pcount) : [];
        $this->assign('auth', $uid == UID ? 1 : 0);     // 验证是否是本人
        $this->assign('docs', $docs);
        $this->assign('did', $did);
        $this->assign('list', $articles['list']);
        $this->assign('page', page($articles['count'], $pcount, $p));
        $this->assign('title', $user['nick'].' - 审阅'.($did ? '[第'.$did.'-'.$p.'页]' : ''));
        $this->assign('description', '用户'.$user['nick'].'的'.($did ? '[第'.$did.'-'.$p.'页]' : '').'审阅记录，展示该用户所有文档的所有审阅信息，其他用户编辑、修改文档之后会展示到该页面！'.$user['desc']);
        $this->display();
    }

    /**
     * 展示用户的贡献度日志记录
     */
    public function log(){
        $p = I('get.p', 1);    //页数
        $pcount = 15;          //每页显示数量
        $result = LogModel::getUserLogHtml(UID, $p, $pcount);;
        $this->assign('html', $result['list']);
        $this->assign('page', page($result['count'], $pcount, $p));
        $this->assign('title', $this->user['nick'].' - 贡献日志'.($p == 1 ? '' : '[第'.$p.'页]'));
        $this->assign('description', '用户'.$this->user['nick'].'的'.($p == 1 ? '所有' : '[第'.$p.'页]').'贡献度日志，清晰明了的展示该用户的贡献度收支明系！'.$this->user['desc']);
        $this->display();
    }

}